package com.ccrfid.rmc6.service.business.nightpatrol;


import com.ccrfid.rmc6.appconfig.exception.pojo.AppException;
import com.ccrfid.rmc6.entity.business.nightpatrol.NpGroupEntity;
import com.ccrfid.rmc6.entity.business.nightpatrol.NpResultEntity;
import com.ccrfid.rmc6.repository.business.nightPatrol.NpGroupRepository;
import com.ccrfid.rmc6.repository.business.nightPatrol.NpResultRepository;
import com.ccrfid.rmc6.util.DateUtil;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Aspect
@Component
public class NightPatrolServiceAspect {
    private static final Logger logger = LoggerFactory.getLogger(NightPatrolServiceAspect.class);

    @Autowired
    private NightPatrolService nightPatrolService;

    @Autowired
    private NpGroupRepository npGroupRepository;

    @Autowired
    private NpResultRepository npResultRepository;


    @Scheduled(cron = "${fixed.delay}")
    public void saveResultInfo() throws AppException {
        logger.info("开始获取保存前一天巡更详情！");
        String preday = getForeDate();

        List<NpGroupEntity> npGroupEntityList = npGroupRepository.getPreNpGroup(preday);
        if (npGroupEntityList.size() > 0) {
            for (int i = 0; i < npGroupEntityList.size(); i++) {
                Long groupId = npGroupEntityList.get(i).getId();
                Date startTime = DateUtil.parseDateTimeStr(preday.toString() + " " + npGroupEntityList.get(i).getStartTimePoint().toString());
                Date stopTime = DateUtil.parseDateTimeStr(preday.toString() + " " + npGroupEntityList.get(i).getEndTimePoint().toString());
                if (npResultRepository.existsByGroupIdAndStartTimeBetween(groupId, startTime, stopTime)) {
                    NpResultEntity resultEntity = npResultRepository.getAllByGroupIdAndStartTimeBetween(groupId, startTime, stopTime);

                    npResultRepository.deleteById(resultEntity.getId());
                }
                nightPatrolService.saveNpResultInfo(groupId, startTime, stopTime);
            }
        }
        logger.info("保存前一天巡更详情结束！");
    }

    //获取前一天日期

    public String getForeDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        Date day = null;
        try {
            day = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ms = day.getTime() - 1 * 24 * 3600 * 1000L;
        Date prevDay = new Date(ms);
        String foreDate = dateFormat.format(prevDay);
        return foreDate;
    }

}
